﻿using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

namespace VFramework{
	/// <summary>
	/// 帧动画类
	/// 将该脚本挂载在图片上，然后拖入相应的精力图片，按顺序
	/// </summary>
	public class VUIFrameAnimation : MonoBehaviour
	{


		public List<Sprite> frames;
		public float frameTime = 0.05f;

		public delegate void DoneHandler ();


		private DoneHandler done = null;
		private int nowFrame = 0;
		private bool run = false;
		private bool autoRemove = false;
		private float timeCount = 0;
		private bool loop = false;


		// Use this for initialization
		void Start ()
		{
			
		}

		public void play (DoneHandler done, bool autoRemove = true, bool loop = false)
		{
			this.done = done;
			this.autoRemove = autoRemove;
			this.loop = loop;
			run = true;
			nowFrame = 0;
			timeCount = 0;
		}

		void stop ()
		{
			
		}
		
		// Update is called once per frame
		void Update ()
		{
			if (run) {
				timeCount += Time.deltaTime;



				if (timeCount >= frameTime) {
					timeCount = 0;
					GetComponent<Image> ().sprite = frames [nowFrame++];
					if (nowFrame >= frames.Count) {
						if (loop) {
							nowFrame = 0;
							return;
						}

						run = false;
						if (this.done != null) {
							this.done.Invoke ();
						}

						if (autoRemove)
							GameObject.DestroyObject (this.gameObject);
					}
				}

			}
		}
	}
}